<?php

namespace app\console;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Env;

/**
 * 异步发送微信消息
 * 运行命令: php think Async
 * 客户端推送demo：
 * $client = new \swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_SYNC);
 * $res = $client->connect('127.0.0.1', 9502);
 * $send_data = ['task_name'=>'import_order', 'data'=>$data, 'log_id'=>$log_id];
 * $client->send(json_encode($send_data));
 */
class Async extends Command
{
    protected function configure()
    {
       $this->setName('Async')->setDescription('Start Web Socket Server!');
    }

    protected function execute(Input $input, Output $output)
    {
        $serv = new \swoole_server('0.0.0.0', 9502);

        $serv->set([
            'task_worker_num' => 4
        ]);

        $serv->on('connect', function ($serv, $fd){
            // echo $fd."客户端已经连接进来了.\n";
        });

        $serv->on('receive', function($serv, $fd, $from_id, $data) {
            $file = Env::get('runtime_path').'log/Async_'.date('Y-m-d').'.log';
            file_put_contents($file, 'data:'.date('Y-m-d H:i:s')."\n".$data, FILE_APPEND);
            $task_id = $serv->task($data);
            // echo "开始投递异步任务 id=$task_id\n";
        });

        $serv->on('task', function ($serv, $task_id, $from_id, $data) {
            echo "开始异步任务[id=$task_id],时间：".date('Y-m-d H:i:s').PHP_EOL;
            $arr = json_decode($data, true);

            //判断任务
            switch ($arr['task_name']) {
                case 'import_order': //订单导入
                    //todo 业务操作
                    echo 'import_order'.PHP_EOL;
                    break;
                case 'import_plan': //计划导入
                    //todo 业务操作
                    echo 'import_plan'.PHP_EOL;
                    break;
                default:
                    # no todo
                    break;
            }
            
            $serv->finish($data);
            unset($arr);
        });

        $serv->on('finish', function ($serv, $task_id, $data) {
            echo "完成异步任务[id=$task_id]，时间：".date('Y-m-d H:i:s').PHP_EOL;
        });
        
        $serv->start();
    }

}